<?php

namespace vico\reservarBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;
use vico\reservarBundle\Entity\Booking;
use vico\reservarBundle\Entity\Product;
use vico\reservarBundle\Entity\Customer;
use vico\reservarBundle\Form\CustomerType;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Response;

class DefaultController extends Controller
{
	public function shoppingcartAction(){
       		$em = $this->getDoctrine()->getManager();
        	$services = $em->getRepository('rsBundle:Service')->findAll();
		$peticion = $this->getRequest();
		$session = $peticion->getSession();
		$session->set('is_already_done',false);
		if($peticion->getMethod() == 'POST'){
			$products_selected = array();
			$products_selected = $peticion->get('products_selected');
			$Shopping_cart_NOT_EMPTY = !(empty($products_selected));
			if($Shopping_cart_NOT_EMPTY){
				$session = $this->getRequest()->getSession();
				$session->set('products_selected',$products_selected);
				return $this->forward('rsBundle:Default:clientform');
			}
			$this->get('session')->getFlashBag()->add(
				'no_services','No ha seleccionado ningún servicio'
			);
		}
		return $this->render('rsBundle:Default:shoppingcart.html.twig',
		array(
		'services'=>$services,
		));
	}
	public function clientformAction(){
		$peticion = $this->getRequest();
        	$customer = new Customer();
        	$form_customer = $this->createCreateForm($customer);
		$form_customer->handleRequest($peticion);
		if($form_customer->isValid()){
			$em = $this->getDoctrine()->getManager();
			$em->persist($customer);
			$em->flush();
			return $this->forward('rsBundle:Default:summary',
			array(
			'customer'=>$customer,
			));
		}
		$session = $this->getRequest()->getSession();
		$products_selected = $session->get('products_selected');
		$session->set('mierdadecabra',$products_selected);
		return $this->render('rsBundle:Default:clientform.html.twig',
		array(
		'form_customer'   => $form_customer->createView(),
		));
	}
	public function summaryAction($customer){

		$session = $this->getRequest()->getSession();

		$is_already_done = $session->get('is_already_done');
		if($is_already_done)
			return new Response('La reserva ya está realizada, revise su correo electrónico para consultar los datos de su reserva.');	

		$session->set('is_already_done',true);

        	$booking = new Booking();
		$peticion = $this->getRequest();
		$comment = $peticion->get('comment');
		$em = $this->getDoctrine()->getManager();
        	$NOT_PAYED = $em->getRepository('rsBundle:Status')->find(1);
		$booking->setStatus($NOT_PAYED);
		$booking->setComment($comment);
		$booking->setCustomer($customer);
		$products_selected = $session->get('mierdadecabra');
		$products = array();
		for($i = 0;$i<count($products_selected);$i++){
        		$products[] = $em->getRepository('rsBundle:Product')->find($products_selected[$i]);
			$acumulated = $booking->getAmount();
			$booking->setAmount($acumulated+$products[$i]->getPrice());
		}
		$booking->setProduct($products);
		$em = $this->getDoctrine()->getManager();
		$em->persist($booking);
		$em->flush();
		$message = \Swift_Message::newInstance()
			->setSubject('Confirmación de Reserva')
			->setFrom('info@grupovico.com')
			->setTo($customer->getEmail())
			->setBody('Este email se envia para confirmar la reserva con codigo '.$booking->getBookcode());
/*				$this->renderView(
				'rsBundle:Default:email_to_confirm_booking.html.twig',
				array('booking' => $booking)	
				));*/
		$this->get('mailer')->send($message);
		return $this->render('rsBundle:Default:summary.html.twig',
		array(
		'bookcode'=>$booking->getBookcode(),
		'customer'=>$customer,
		'booking'=>$booking,
		));
	}
	public function bookingStatusAction(){
		$peticion = $this->getRequest();
		if($peticion->isMethod('POST')){
        		$em = $this->getDoctrine()->getManager();
			$bookCode = $peticion->request->get('bookcode');
			$booking = $em->getRepository('rsBundle:Booking')->findOneBy(
			array(
			'bookcode'=>$bookCode,	
			));
			return $this->render('rsBundle:Default:showStatusBooking.html.twig',
			array(
			'booking'=>$booking,
			));
		}
		return $this->render('rsBundle:Default:searchStatusBooking.html.twig', array(
		));
	}
	private function createCreateForm(Customer $entity)
	{
        $form = $this->createForm(new CustomerType(), $entity, array(
            'action' => $this->generateUrl('rs_summary'),
            'method' => 'POST',
        ));
		$form->add('submit', 'submit', 
			array(
			'label' => 'Siguiente',
			'attr'=>array(
			'class'=>'btn btn-lg btn-info',
			'style' => 'margin: 10px; float: right;'
				)	
			)
		);
        return $form;
    }

    public function indexAction()
    {
        return $this->render('rsBundle:Default:index.html.twig', array());
    }

    public function loginAction(){
	$peticion = $this->getRequest();
        $sesion = $peticion->getSession();
 
        $error = $peticion->attributes->get(
            SecurityContext::AUTHENTICATION_ERROR,
            $sesion->get(SecurityContext::AUTHENTICATION_ERROR)
        );
 
        return $this->render('rsBundle:Default:login.html.twig', array(
            'last_username' => $sesion->get(SecurityContext::LAST_USERNAME),
            'error'         => $error
        ));
    }					
	public function probarmailAction(){
		mail('pedrocantoria@gmail.com', "usando funcion mail", "Esta email se ha enviado usando la funcion mail() de php");
		$message = \Swift_Message::newInstance()
			->setSubject('usando funcion mail de symfony')
			->setFrom('info@grupovico.com')
			->setTo('pedrocantoria@gmail.com')
			->setBody('Este email se ha enviado usando la función mail() de Symfony2');
			$this->get('mailer')->send($message);
		return new Response('Se ha enviado un mail');
	}
				
}
